﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;

using DotNetNuke.Entities.Tabs;
using iFinity.DNN.Modules.UrlMaster;
using iFinity.DNN.Modules.UrlMaster.Entities;
using iFinity.DNN.Modules.CatalookUrlProvider.Entities;

namespace iFinity.DNN.Modules.CatalookUrlProvider.UI
{
    /// <summary>
    /// This is the code-behind for the Settings.ascx control.  This inherits from the standard .NET UserControl, but also implements the ModuleProvider specific IProviderSettings.
    /// This control will be loaded by the Portal Urls page.  It is optional for module providers, but allows users to control module settings via the interface, rather than 
    /// having to set options via web.config settings.  The writing / reading of the items from the configuration file is handled by the Url Master module, and doesn't need to 
    /// be implemented.
    /// </summary>
    public partial class Settings : System.Web.UI.UserControl, IProviderSettings
    {
        private int _portalId;
        #region controls
        protected Label lblHeader;
        //protected TextBox txtUrlPath;
        protected TextBox txtStartingProductId;
        protected DropDownList ddlNoDnnPagePathTab;
        protected DropDownList ddlProductUrlSource  ;
        protected DropDownList ddlCategoryUrlSource;
        protected DropDownList ddlAdvCatUrlSource;
        protected CheckBox chkHideListParm;
        protected DropDownList ddlListParmToHide;
        protected CheckBox chkHideCategoryForProducts;
        protected Label lblSettings;
        
        protected CheckBox chkProductIdInUrl;

        

        #endregion
        #region Web Form Designer Generated Code
        //[System.Diagnostics.DebuggerStepThrough]
        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        ///		Required method for Designer support - do not modify
        ///		the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
        }

        #endregion
        #region events code
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                //note page load runs after LoadSettings(); because of dynamic control loading
                //these values match the .dnn manifest package definitions

                //now get the javascript in
                ScriptController.InjectjQueryLibary(this.Page, true, true);
                //module-specific jquery code
                ScriptController.InjectJsLibrary(this.Page, "cup", this.ControlPath + "/js/cup.js", true, ScriptController.ScriptInjectOrder.e_Default);
                //and get the css file in
                ScriptController.InjectCssReference(this.Page, "cup_css", this.ControlPath + "/cup.css", true, ScriptController.CssInjectOrder.f_Last);
                //and put in a pre-dnn 6 ui script plus the jquery tabs library
                string preDnn6CssFile = this.ControlPath + "/ui-tabs.css";
                ScriptController.InjectjQueryTabsCss(this.Page, preDnn6CssFile, null);

            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, ex);
            }
        }
        #endregion
        #region content methods
        private void LocalizeControls()
        {
            try
            {
                lblHeader.Text = DotNetNuke.Services.Localization.Localization.GetString("Header.Text",
                                                                                         this.LocalResourceFile);


                //only publicly available non-admin or host tabs are used.
                TabController tc = new TabController();
                //load tabs into drop down list            
                TabCollection tabs = tc.GetTabsByPortal(_portalId);
                //loop through the tabs and add the ones that aren't admin or host tabs
                ddlNoDnnPagePathTab.Items.Clear();
                string firstItem = DotNetNuke.Services.Localization.Localization.GetString("NoTabSelected.Text",
                                                                                           this.LocalResourceFile);
                ddlNoDnnPagePathTab.Items.Add(new ListItem(firstItem, "-1"));
                foreach (TabInfo tab in tabs.Values)
                {
                    if (tab.IsSuperTab == false) //TODO: filter admin tabs as well?
                        ddlNoDnnPagePathTab.Items.Add(new ListItem(tab.TabName, tab.TabID.ToString()));
                }

                List<string> urlSources = EnumConversion.ReturnEnumAsList(typeof (UrlSource));
                BindDropDownList(urlSources, ddlAdvCatUrlSource);
                BindDropDownList(urlSources, ddlCategoryUrlSource);
                BindDropDownList(urlSources, ddlProductUrlSource);

                ddlListParmToHide.Items.Clear();
                ddlListParmToHide.Items.Add(new ListItem("List=0", "0"));
                ddlListParmToHide.Items.Add(new ListItem("List=1", "1"));
            }
            catch (Exception ex)
            {
                //suppress exception to let page load
            }
        }
        private void BindDropDownList(List<string> values, DropDownList ddlList)
        {
            foreach (string val in values)
            {
                string text = DotNetNuke.Services.Localization.Localization.GetString(val + ".Text", this.LocalResourceFile);
                if (text == null || text == "")
                    text = val;

                ddlList.Items.Add(new ListItem(text, val));
            }
        }
        private void SetDropDownList(DropDownList ddlList, string selValue)
        {
            ListItem item = ddlList.Items.FindByValue(selValue);
            if (item != null)
                ddlList.SelectedValue = selValue;
            else
                if (ddlList.Items.Count > 0)
                    ddlList.SelectedIndex = 0;

        }
        #endregion
        #region IProviderSettings Members
        /// <summary>
        /// LoadSettings is called when the module control is first loaded onto the page
        /// </summary>
        /// <remarks>
        /// This method shoudl read all the custom properties of the provider and set the controls
        /// of the page to reflect the current settings of the provider.
        /// </remarks>
        /// <param name="provider"></param>
        public void LoadSettings(iFinity.DNN.Modules.UrlMaster.ModuleFriendlyUrlProvider provider)
        {
            //build list of controls
            if (!IsPostBack)
                LocalizeControls();
            //take all the values from the provider and show on page
            //check type safety before cast
            if (provider.GetType() == typeof(CatalookModuleProvider))
            {
                CatalookModuleProvider moduleProvider = (CatalookModuleProvider)provider;
                
                //txtUrlPath.Text = moduleProvider.UrlPath;
                
                string selTabId = moduleProvider.NoDnnPagePathTabId.ToString();
                SetDropDownList(ddlNoDnnPagePathTab, selTabId);
                
                if (moduleProvider.StartingProductId > 0)
                    txtStartingProductId.Text = moduleProvider.StartingProductId.ToString();
                else
                    txtStartingProductId.Text = "";

                //set source values
                SetDropDownList(ddlProductUrlSource, moduleProvider.ProductUrlSource);
                SetDropDownList(ddlCategoryUrlSource, moduleProvider.CategoryUrlSource);
                SetDropDownList(ddlAdvCatUrlSource, moduleProvider.AdvCatUrlSource);
                SetDropDownList(ddlListParmToHide, moduleProvider.ListParmToHide.ToString());
                chkHideCategoryForProducts.Checked = moduleProvider.HideCategoryForProducts;
                chkHideListParm.Checked = moduleProvider.HideListParm;
                chkProductIdInUrl.Checked = moduleProvider.ProductIdInUrl;
            }
        }


        /// <summary>
        /// UpdateSettings is called when the 'update' button is clicked on the interface.
        /// This should take any values from the page, and set the individual properties on the 
        /// instance of the module provider.
        /// </summary>
        /// <param name="provider"></param>
        public void UpdateSettings(iFinity.DNN.Modules.UrlMaster.ModuleFriendlyUrlProvider provider)
        {
            //check type safety before cast
            if (provider.GetType() == typeof(CatalookModuleProvider))
            {
                //take values from the page and set values on provider    
                CatalookModuleProvider moduleProvider = (CatalookModuleProvider)provider;
                
                //moduleProvider.UrlPath = txtUrlPath.Text;
                
                string rawTabId = ddlNoDnnPagePathTab.SelectedValue;
                int selTabId;
                moduleProvider.NoDnnPagePathTabId = 0;
                if (int.TryParse(rawTabId, out selTabId))
                {
                    if (selTabId > 0)
                        moduleProvider.NoDnnPagePathTabId = selTabId;
                }

                int startingProductId = 0;
                moduleProvider.StartingProductId = 0;
                if (int.TryParse(txtStartingProductId.Text, out startingProductId))
                {
                    if (startingProductId > 0)
                        moduleProvider.StartingProductId = startingProductId;
                }

                moduleProvider.ProductUrlSource = ddlProductUrlSource.SelectedValue;
                moduleProvider.CategoryUrlSource = ddlCategoryUrlSource.SelectedValue;
                moduleProvider.AdvCatUrlSource = ddlCategoryUrlSource.SelectedValue;
                moduleProvider.HideListParm = chkHideListParm.Checked;
                moduleProvider.HideCategoryForProducts = chkHideCategoryForProducts.Checked;
                moduleProvider.ProductIdInUrl = chkProductIdInUrl.Checked;
                int listParmToHide = 0;
                if (int.TryParse(ddlListParmToHide.SelectedValue, out listParmToHide))
                    moduleProvider.ListParmToHide = listParmToHide;
                else
                    moduleProvider.ListParmToHide = -1;
                
            }

        }
        
        public System.Web.UI.Control Control
        {
            get { return this;  }
        }

        public string ControlPath
        {
            get { return base.TemplateSourceDirectory; }
        }

        public string ControlName
        {
            get { return "ProviderSettings";  }
        }

        public string LocalResourceFile
        {
            get { return "DesktopModules/iFinity.CatalookUrlProvider/App_LocalResources/Settings.ascx.resx"; }
        }
        public int PortalId
        {
            get { return _portalId; }
            set { _portalId = value; }
        }

        #endregion

    }
}
